"""基于LegalBERT的题目生成器"""
from typing import List, Dict, Any, Optional
from app.ai.legalbert_service import get_legalbert_service
from app.db.question_bank import QUESTION_BANK, SUBJECT_WEIGHTS, get_questions_by_subject
from app.services.user_level_service import user_level_service
from app.services.difficulty_service import difficulty_service
from app.core.database import RedisClient
from app.ai.llm_question_generator import llm_question_generator


class QuestionGenerator:
    """题目生成器 - 结合题库和LegalBERT"""
    
    def __init__(self):
        self.legalbert = get_legalbert_service()
        self.question_bank = QUESTION_BANK
        try:
            self.redis = RedisClient.get_client()
            self.redis.ping()
        except Exception as e:
            print(f"警告: Redis连接失败: {e}")
            self.redis = None
    
    async def recommend_questions(
        self,
        user_id: str,
        count: int = 10,
        subject_distribution: Optional[Dict[str, float]] = None,
        difficulty: Optional[str] = None,
        exclude_question_ids: Optional[List[str]] = None,
        include_review_questions: bool = True,
        review_ratio: float = 0.2
    ) -> List[str]:
        """
        根据权重推荐题目（支持动态难度和错题优先）
        
        Args:
            user_id: 用户ID
            count: 推荐数量
            subject_distribution: 科目分布（如果None则使用默认权重）
            difficulty: 难度过滤（如果None则根据用户水平动态确定）
            exclude_question_ids: 排除的题目ID
            
        Returns:
            推荐的题目ID列表
        """
        if subject_distribution is None:
            # 使用科目英文标识映射到权重
            subject_distribution = {
                "civil_law": 0.18,      # 民法
                "civil_procedure": 0.12,  # 民诉
                "criminal_law": 0.15,    # 刑法
                "criminal_procedure": 0.10,  # 刑诉
                "administrative": 0.12,   # 行政
                "commercial": 0.15,      # 商经
                "international": 0.08,    # 三国
                "comprehensive": 0.10     # 综合
            }
        
        # 如果没有指定难度，根据用户水平动态确定
        if difficulty is None:
            user_level = user_level_service.get_user_level(user_id)
            difficulty = user_level.get("recommended_difficulty", "medium")
            print(f"🔍 [题目推荐] 用户 {user_id} 当前水平: {user_level.get('current_difficulty')}, 推荐难度: {difficulty}")
        
        # 计算每个科目应该推荐的题目数量
        recommended = []
        
        # 优先从Redis获取所有题目，如果Redis没有则使用内存题库
        available_questions = []
        try:
            from app.services.question_storage_service import question_storage_service
            from app.db.question_bank import get_all_questions
            
            # 优先从Redis读取
            redis_questions = question_storage_service.get_all_questions()
            if redis_questions and len(redis_questions) > 0:
                available_questions = redis_questions
                print(f"✅ [题目推荐] 从Redis获取 {len(available_questions)} 道题目")
            else:
                # Redis没有，使用内存题库（包含Redis和内存的合并结果）
                available_questions = get_all_questions()
                print(f"✅ [题目推荐] 从内存获取 {len(available_questions)} 道题目")
        except Exception as e:
            print(f"⚠️ [题目推荐] 获取题目失败，使用内存题库: {e}")
            available_questions = self.question_bank.copy()
        
        # 分离新题目和旧题目
        exclude_set = set(exclude_question_ids) if exclude_question_ids else set()
        
        # 获取用户做过的题目记录（用于区分新题和旧题）
        done_questions = {}  # {question_id: {"wrong_count": int, "correct_count": int}}
        if exclude_set:
            # 从题目数据中获取做错/做对次数
            for q in available_questions:
                qid = q.get("question_id")
                if qid in exclude_set:
                    done_questions[qid] = {
                        "wrong_count": q.get("wrong_count", 0),
                        "correct_count": q.get("correct_count", 0)
                    }
        
        # 分离新题目（未做过的）和旧题目（做过的）
        new_questions = [q for q in available_questions if q.get("question_id") not in exclude_set]
        old_questions = [q for q in available_questions if q.get("question_id") in exclude_set]
        
        # 如果include_review_questions为False，只使用新题目
        if not include_review_questions:
            available_questions = new_questions
        # 如果启用复习题目，保留所有题目，但会在后面按比例选择
        
        # 按难度过滤（如果指定了难度）
        # 注意：如果过滤后题目太少，放宽条件
        if difficulty:
            filtered_by_difficulty = [
                q for q in available_questions 
                if difficulty_service.get_difficulty_level(q.get("question_id")) == difficulty
            ]
            # 如果过滤后题目数量不足，放宽难度要求（允许相邻难度）
            if len(filtered_by_difficulty) < count * 2:
                # 允许相邻难度：easy可以包含medium，medium可以包含easy和hard，hard可以包含medium
                difficulty_map = {
                    "easy": ["easy", "medium"],
                    "medium": ["easy", "medium", "hard"],
                    "hard": ["medium", "hard"]
                }
                allowed_difficulties = difficulty_map.get(difficulty, [difficulty])
                filtered_by_difficulty = [
                    q for q in available_questions 
                    if difficulty_service.get_difficulty_level(q.get("question_id")) in allowed_difficulties
                ]
            available_questions = filtered_by_difficulty
        
        # 如果仍然没有可用题目，尝试不按难度过滤
        if not available_questions:
            print(f"⚠️ [题目推荐] 按难度 {difficulty} 过滤后无题目，尝试不按难度过滤")
            # 重新获取所有题目（不按难度过滤）
            try:
                from app.services.question_storage_service import question_storage_service
                from app.db.question_bank import get_all_questions
                redis_questions = question_storage_service.get_all_questions()
                if redis_questions and len(redis_questions) > 0:
                    available_questions = redis_questions
                else:
                    available_questions = get_all_questions()
                # 排除已做过的题目
                exclude_set = set(exclude_question_ids) if exclude_question_ids else set()
                available_questions = [
                    q for q in available_questions 
                    if q.get("question_id") not in exclude_set
                ]
            except Exception as e:
                print(f"⚠️ [题目推荐] 重新获取题目失败: {e}")
                available_questions = self.question_bank.copy()
        
        # 如果还是没有可用题目，返回空列表
        if not available_questions:
            print(f"❌ [题目推荐] 无可用题目")
            return []
        
        # 计算题目权重（错题优先，做对题目降低权重）
        question_weights = []
        for q in available_questions:
            qid = q.get("question_id")
            base_weight = 1.0
            
            # 获取题目的做错/做对次数
            wrong_count = q.get("wrong_count", 0)
            correct_count = q.get("correct_count", 0)
            
            # 错题优先：做错次数越多，权重越高
            if wrong_count > 0:
                base_weight = 2.0 + (wrong_count * 0.5)  # 错题基础权重2.0，每错一次+0.5
                # 如果做对过，降低权重，但保证不低于1.5（确保错题始终优先于未做过的题目）
                if correct_count > 0:
                    base_weight = max(1.5, base_weight * (0.5 ** min(correct_count, 2)))
            elif correct_count > 0:
                # 只做对过，没有做错：降低权重（但不完全排除）
                base_weight = 1.0 * (0.3 ** min(correct_count, 3))
            else:
                # 从未做过的题目保持正常权重
                base_weight = 1.0
            
            question_weights.append({
                "question_id": qid,
                "question": q,
                "weight": base_weight
            })
        
        # 如果启用了复习题目，按比例分配新题和旧题（80%新题，20%旧题）
        if include_review_questions and len(old_questions) > 0:
            new_count = int(count * (1 - review_ratio))  # 80%新题目
            review_count = count - new_count  # 20%旧题目
            
            # 重新计算权重，分离新题和旧题的权重
            new_question_weights = []
            review_question_weights = []
            
            for item in question_weights:
                qid = item["question_id"]
                if qid in exclude_set:
                    # 这是做过的题目（旧题）
                    q = item["question"]
                    weight = 1.0
                    wrong_count = done_questions.get(qid, {}).get("wrong_count", 0)
                    correct_count = done_questions.get(qid, {}).get("correct_count", 0)
                    
                    # 错题优先：做错次数越多，权重越高
                    if wrong_count > 0:
                        weight = 3.0 + (wrong_count * 0.5)  # 错题权重高
                        if correct_count > 0:
                            weight = max(2.0, weight * (0.5 ** min(correct_count, 2)))
                    elif correct_count > 0:
                        # 只做对过：降低权重（做对次数越多，权重越低）
                        weight = 0.5 * (0.3 ** min(correct_count, 3))
                    
                    review_question_weights.append({
                        "question_id": qid,
                        "question": q,
                        "weight": weight
                    })
                else:
                    # 这是新题目
                    new_question_weights.append(item)
            
            # 按权重排序
            new_question_weights.sort(key=lambda x: x["weight"], reverse=True)
            review_question_weights.sort(key=lambda x: x["weight"], reverse=True)
            
            # 从新题目中选择
            new_selected = []
            for item in new_question_weights:
                if len(new_selected) >= new_count:
                    break
                qid = item["question_id"]
                if qid not in exclude_set:
                    new_selected.append(qid)
            
            # 从旧题目中选择（错题优先）
            review_selected = []
            for item in review_question_weights:
                if len(review_selected) >= review_count:
                    break
                qid = item["question_id"]
                if qid not in set(new_selected):
                    review_selected.append(qid)
            
            # 合并新题和旧题
            recommended = new_selected + review_selected
            print(f"📊 [题目推荐] 新题目: {len(new_selected)} 道 ({len(new_selected)/count*100:.0f}%), 复习题目: {len(review_selected)} 道 ({len(review_selected)/count*100:.0f}%, 错题优先)")
        else:
            # 不使用复习题目，只从新题目中选择（按科目权重分配）
            selected_ids = set()
            for subject, weight in subject_distribution.items():
                if weight <= 0 or len(recommended) >= count:
                    break
                    
                subject_count = max(1, int(count * weight))
                subject_selected = []
                
                # 从该科目的题目中按权重选择（只选新题）
                for item in question_weights:
                    if len(subject_selected) >= subject_count:
                        break
                    
                    q = item["question"]
                    qid = item["question_id"]
                    
                    # 跳过做过的题目
                    if qid in exclude_set:
                        continue
                    
                    # 检查是否属于该科目
                    q_subject = q.get("subject", "")
                    q_category = q.get("category", "")
                    
                    is_match = False
                    if q_subject == subject:
                        is_match = True
                    elif subject == "comprehensive":
                        if not q_category or q_category == "" or q_category == "综合":
                            is_match = True
                    elif q_category:
                        from app.db.question_bank import SUBJECT_NAMES
                        subject_name = SUBJECT_NAMES.get(subject, "")
                        if subject_name and q_category == subject_name:
                            is_match = True
                    
                    if is_match:
                        if qid not in selected_ids:
                            subject_selected.append(qid)
                            selected_ids.add(qid)
                
                recommended.extend(subject_selected)
            
            # 如果推荐数量不足，补充其他新题目（按权重排序）
            if len(recommended) < count:
                remaining = []
                recommended_set = set(recommended)
                for item in question_weights:
                    qid = item["question_id"]
                    if qid not in recommended_set and qid not in exclude_set:
                        remaining.append(qid)
                    if len(remaining) >= (count - len(recommended)):
                        break
                recommended.extend(remaining)
        
        # 随机打乱最终结果（保持权重优先级的同时增加随机性）
        random.shuffle(recommended[:count])
        
        return recommended[:count]
    
    async def recommend_questions_with_llm(
        self,
        user_id: str,
        count: int = 10,
        exclude_question_ids: Optional[List[str]] = None
    ) -> List[str]:
        """
        使用大模型智能推荐题目（基于用户学习历史和薄弱环节）
        
        Args:
            user_id: 用户ID
            count: 推荐数量
            exclude_question_ids: 排除的题目ID
            
        Returns:
            推荐的题目ID列表
        """
        try:
            from app.ai.llm_service import get_llm_service
            from app.services.progress_service import progress_service
            from app.services.user_level_service import user_level_service
            
            # 获取用户学习情况
            user_level = user_level_service.get_user_level(user_id)
            weakness_analysis = await progress_service.get_weakness_analysis(user_id)
            
            # 获取可用题目
            available_questions = []
            try:
                from app.services.question_storage_service import question_storage_service
                from app.db.question_bank import get_all_questions
                
                redis_questions = question_storage_service.get_all_questions()
                if redis_questions and len(redis_questions) > 0:
                    available_questions = redis_questions
                else:
                    available_questions = get_all_questions()
            except Exception as e:
                print(f"⚠️ [智能推荐] 获取题目失败: {e}")
                available_questions = self.question_bank.copy()
            
            # 排除已做过的题目
            exclude_set = set(exclude_question_ids) if exclude_question_ids else set()
            available_questions = [
                q for q in available_questions 
                if q.get("question_id") not in exclude_set
            ]
            
            if not available_questions:
                print("⚠️ [智能推荐] 无可用题目，回退到基础推荐")
                return await self.recommend_questions(user_id, count, exclude_question_ids=exclude_question_ids)
            
            # 构建题目信息摘要（用于大模型分析）
            question_summaries = []
            for q in available_questions[:200]:  # 限制数量，避免prompt过长
                qid = q.get("question_id", "")
                subject = q.get("subject", "") or q.get("category", "")
                difficulty = q.get("difficulty", "medium")
                knowledge_points = ", ".join(q.get("knowledge_points", [])[:3])  # 只取前3个知识点
                
                question_summaries.append({
                    "id": qid,
                    "subject": subject,
                    "difficulty": difficulty,
                    "knowledge_points": knowledge_points
                })
            
            # 构建prompt
            weak_subjects = [w.get("subject", "") for w in weakness_analysis.get("weak_subjects", [])]
            weak_knowledge_points = [w.get("knowledge_point", "") for w in weakness_analysis.get("weak_knowledge_points", [])]
            current_difficulty = user_level.get("current_difficulty", "medium")
            recommended_difficulty = user_level.get("recommended_difficulty", "medium")
            
            prompt = f"""你是一位法律考试学习助手。请根据用户的学习情况，智能推荐最适合的题目。

用户学习情况：
- 当前适合难度：{current_difficulty}
- 推荐难度：{recommended_difficulty}
- 薄弱科目：{', '.join(weak_subjects[:5]) if weak_subjects else '暂无'}
- 薄弱知识点：{', '.join(weak_knowledge_points[:5]) if weak_knowledge_points else '暂无'}

可用题目列表（共{len(question_summaries)}道）：
"""
            
            # 添加题目摘要（限制长度）
            for i, q_summary in enumerate(question_summaries[:100]):  # 只取前100道题
                prompt += f"{i+1}. ID: {q_summary['id']}, 科目: {q_summary['subject']}, 难度: {q_summary['difficulty']}, 知识点: {q_summary['knowledge_points']}\n"
            
            prompt += f"""
请根据以下原则推荐 {count} 道题目：
1. 优先推荐薄弱科目和薄弱知识点的题目
2. 难度应该适合用户当前水平（推荐难度：{recommended_difficulty}）
3. 题目应该多样化，覆盖不同知识点
4. 优先推荐用户未做过的题目

请只返回题目ID列表，格式：["question_id1", "question_id2", ...]
只返回JSON数组，不要其他文字说明。
"""
            
            # 调用大模型
            llm_service = get_llm_service()
            response_text = await llm_service.generate_text(
                prompt,
                max_tokens=500,
                temperature=0.3  # 降低温度，提高确定性
            )
            
            # 解析响应
            import json
            import re
            
            # 尝试提取JSON数组
            json_match = re.search(r'\[.*?\]', response_text, re.DOTALL)
            if json_match:
                try:
                    recommended_ids = json.loads(json_match.group())
                    # 验证题目ID是否有效
                    valid_ids = []
                    available_id_set = {q.get("question_id") for q in available_questions}
                    
                    for qid in recommended_ids:
                        if isinstance(qid, str) and qid in available_id_set:
                            valid_ids.append(qid)
                        if len(valid_ids) >= count:
                            break
                    
                    if valid_ids:
                        print(f"✅ [智能推荐] 大模型推荐了 {len(valid_ids)} 道题目")
                        return valid_ids
                except Exception as e:
                    print(f"⚠️ [智能推荐] 解析大模型响应失败: {e}")
            
            # 如果大模型推荐失败，回退到基础推荐
            print("⚠️ [智能推荐] 大模型推荐失败，回退到基础推荐")
            return await self.recommend_questions(user_id, count, exclude_question_ids=exclude_question_ids)
            
        except Exception as e:
            print(f"⚠️ [智能推荐] 使用大模型推荐失败: {e}，回退到基础推荐")
            # 回退到基础推荐方法
            return await self.recommend_questions(user_id, count, exclude_question_ids=exclude_question_ids)
    
    async def generate_questions_with_llm(
        self,
        user_id: str,
        count: int = 10,
        subject_distribution: Optional[Dict[str, float]] = None,
        difficulty: Optional[str] = None,
        weakness_analysis: Optional[Dict[str, Any]] = None,
        progressive_training: bool = True
    ) -> List[Dict[str, Any]]:
        """
        使用LLM动态生成题目，按照法考科目权重，从简单到复杂渐进训练
        
        Args:
            user_id: 用户ID
            count: 生成数量
            subject_distribution: 科目分布（如果None则使用法考标准权重）
            difficulty: 难度（如果None则根据用户水平动态确定）
            weakness_analysis: 薄弱环节分析（可选）
            progressive_training: 是否启用渐进式训练（从简单到复杂）
            
        Returns:
            生成的题目列表（按难度排序）
        """
        try:
            # 获取用户水平
            user_level = user_level_service.get_user_level(user_id)
            base_difficulty = difficulty or user_level.get("recommended_difficulty", "medium")
            
            # 使用法考标准科目权重
            if subject_distribution is None:
                from app.db.question_bank import SUBJECT_WEIGHTS
                subject_distribution = SUBJECT_WEIGHTS.copy()
            
            # 获取薄弱科目和知识点
            weak_subjects = []
            weak_knowledge_points = []
            
            if weakness_analysis:
                weak_subjects = weakness_analysis.get("weak_subjects", [])
                weak_knowledge_points = weakness_analysis.get("weak_knowledge_points", [])
            
            # 如果启用渐进式训练，计算难度分布
            if progressive_training:
                # 难度分布：简单40%，中等40%，困难20%
                difficulty_distribution = {
                    "easy": 0.4,
                    "medium": 0.4,
                    "hard": 0.2
                }
            else:
                # 不使用渐进式训练，全部使用基础难度
                difficulty_distribution = {base_difficulty: 1.0}
            
            # 构建生成要求（按科目权重 + 难度分布）
            requirements = []
            
            for subject, subject_weight in subject_distribution.items():
                if subject_weight <= 0:
                    continue
                
                # 计算该科目应生成的题目总数
                subject_total_count = max(1, int(count * subject_weight))
                
                # 如果启用渐进式训练，按难度分布生成
                if progressive_training:
                    for diff_level, diff_weight in difficulty_distribution.items():
                        subject_count = max(1, int(subject_total_count * diff_weight))
                        if subject_count > 0:
                            # 选择知识点
                            knowledge_point = self._get_knowledge_point_for_subject(
                                subject, weak_knowledge_points
                            )
                            
                            requirements.append({
                                "subject": subject,
                                "knowledge_point": knowledge_point,
                                "difficulty": diff_level,
                                "question_type": "single_choice",
                                "count": subject_count,
                                "sort_order": self._get_difficulty_order(diff_level)  # 用于排序
                            })
                else:
                    # 不使用渐进式训练，全部使用基础难度
                    knowledge_point = self._get_knowledge_point_for_subject(
                        subject, weak_knowledge_points
                    )
                    requirements.append({
                        "subject": subject,
                        "knowledge_point": knowledge_point,
                        "difficulty": base_difficulty,
                        "question_type": "single_choice",
                        "count": subject_total_count,
                        "sort_order": self._get_difficulty_order(base_difficulty)
                    })
            
            # 按难度排序（简单->中等->困难）
            requirements.sort(key=lambda x: x.get("sort_order", 0))
            
            # 批量生成题目
            print(f"🤖 [LLM生成] 开始生成 {count} 道题目（按法考科目权重，渐进式训练）...")
            generated_questions = await llm_question_generator.generate_questions_batch(requirements)
            
            # 验证和过滤题目
            valid_questions = []
            for question in generated_questions:
                is_valid, error_msg = llm_question_generator.validate_question(question)
                if is_valid:
                    valid_questions.append(question)
                else:
                    print(f"⚠️ [LLM生成] 题目验证失败: {error_msg}")
            
            # 按难度排序（简单->中等->困难）
            if progressive_training:
                valid_questions.sort(key=lambda q: self._get_difficulty_order(
                    q.get("difficulty", "medium")
                ))
            
            # 如果生成数量不足，补充生成
            if len(valid_questions) < count:
                remaining = count - len(valid_questions)
                print(f"⚠️ [LLM生成] 生成数量不足，补充生成 {remaining} 道题目...")
                
                # 使用默认要求补充生成（从简单开始）
                for i in range(remaining):
                    # 轮换难度
                    if progressive_training:
                        diff_levels = ["easy", "medium", "hard"]
                        diff_index = i % len(diff_levels)
                        difficulty_to_use = diff_levels[diff_index]
                    else:
                        difficulty_to_use = base_difficulty
                    
                    question = await llm_question_generator.generate_question(
                        subject="民法",
                        knowledge_point="合同法",
                        difficulty=difficulty_to_use
                    )
                    if question:
                        is_valid, _ = llm_question_generator.validate_question(question)
                        if is_valid:
                            valid_questions.append(question)
                
                # 再次排序
                if progressive_training:
                    valid_questions.sort(key=lambda q: self._get_difficulty_order(
                        q.get("difficulty", "medium")
                    ))
            
            print(f"✅ [LLM生成] 成功生成 {len(valid_questions)} 道有效题目")
            print(f"📊 [LLM生成] 难度分布: 简单={sum(1 for q in valid_questions if q.get('difficulty')=='easy')}, "
                  f"中等={sum(1 for q in valid_questions if q.get('difficulty')=='medium')}, "
                  f"困难={sum(1 for q in valid_questions if q.get('difficulty')=='hard')}")
            
            return valid_questions[:count]
            
        except Exception as e:
            print(f"❌ [LLM生成] 生成题目失败: {e}")
            import traceback
            traceback.print_exc()
            return []
    
    def _get_knowledge_point_for_subject(
        self,
        subject: str,
        weak_knowledge_points: List[str]
    ) -> str:
        """为科目选择合适的知识点"""
        # 科目知识点映射
        subject_knowledge_map = {
            "民法": ["合同法", "物权法", "侵权责任法", "婚姻家庭法"],
            "民诉": ["管辖", "诉讼程序", "证据", "执行程序"],
            "刑法": ["犯罪构成", "刑罚", "分则", "共同犯罪"],
            "刑诉": ["立案", "侦查", "起诉", "审判程序"],
            "行政": ["行政许可", "行政处罚", "行政复议", "行政诉讼"],
            "商经": ["公司法", "合伙企业法", "破产法", "知识产权法"],
            "三国": ["国际公法", "国际私法", "国际经济法"],
            "综合": ["综合案例分析", "跨科目综合"]
        }
        
        # 优先使用薄弱知识点
        if weak_knowledge_points:
            for kp in weak_knowledge_points:
                if any(kw in kp for kw in [subject, subject[:2]]):
                    return kp
        
        # 使用默认知识点
        default_points = subject_knowledge_map.get(subject, ["基础理论"])
        return default_points[0]
    
    def _get_difficulty_order(self, difficulty: str) -> int:
        """获取难度排序值（用于排序：简单->中等->困难）"""
        order_map = {
            "easy": 1,
            "medium": 2,
            "hard": 3
        }
        return order_map.get(difficulty, 2)
    
    async def generate_question_by_subject(
        self,
        subject: str,
        knowledge_point: str,
        difficulty: str = "medium"
    ) -> Dict[str, Any]:
        """
        为特定科目生成题目（使用LegalBERT增强）
        
        Args:
            subject: 科目
            knowledge_point: 知识点
            difficulty: 难度
            
        Returns:
            生成的题目
        """
        # 先尝试从题库中查找
        existing_questions = get_questions_by_subject(subject)
        if existing_questions:
            # 可以基于现有题目进行改写或增强
            pass
        
        # 使用LegalBERT生成新题目
        generated = await self.legalbert.generate_question(
            subject, knowledge_point, difficulty
        )
        
        return generated
    
    def get_question_statistics(self) -> Dict[str, Any]:
        """获取题库统计信息"""
        from app.db.question_bank import get_question_count_by_subject
        
        stats = {
            "total_questions": len(self.question_bank),
            "by_subject": get_question_count_by_subject(),
            "by_difficulty": {},
            "by_category": {}
        }
        
        # 统计难度分布
        for q in self.question_bank:
            diff = q.get("difficulty", "unknown")
            stats["by_difficulty"][diff] = stats["by_difficulty"].get(diff, 0) + 1
        
        # 统计分类分布
        for q in self.question_bank:
            cat = q.get("category", "unknown")
            stats["by_category"][cat] = stats["by_category"].get(cat, 0) + 1
        
        return stats


question_generator = QuestionGenerator()

